package com.css.fxfzdpzs.modules.dzzh.service;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdpzs.modules.czt.bo.PsCurveBo;
import com.css.fxfzdpzs.modules.czt.param.ProbabilisticEarthquakeParam;
import com.css.fxfzdpzs.modules.czt.vo.PeCurveVo;
import com.css.fxfzdpzs.modules.dzzh.entity.first.*;
import com.css.fxfzdpzs.modules.dzzh.entity.repository.DzzhRepository;
import com.css.fxfzdpzs.modules.dzzh.entity.first.DzzhMapEarthquakeDisaster;
import com.css.fxfzdpzs.modules.dzzh.entity.second.DpzsVO;
import com.css.fxfzdpzs.modules.dzzh.entity.second.EarthquakeDisasterNum;
import com.css.fxfzdpzs.modules.dzzh.param.LargeScreenParam;
import com.css.fxfzdpzs.modules.dzzh.param.ZoneParam;
import com.css.fxfzdpzs.modules.dzzh.vo.*;
import com.css.fxfzdpzs.modules.fxpg.entity.AssessQh;
import com.css.fxfzdpzs.modules.xczh.entity.first.DisasterVisitsCount;
import com.css.fxfzdpzs.modules.xczh.repository.XczhRepository;
import com.css.fxfzdpzs.util.PlatformObjectUtils;
import com.css.fxfzdpzs.util.RestTemplateUtil;
import com.css.fxfzdpzs.util.UUIDGenerator;
import com.css.fxfzdpzs.zcpt.sys.service.SysAreaService;
import com.css.fxfzdpzs.util.UUIDGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author y1fan
 * @description
 */
@Service
public class DzzhServiceImpl implements DzzhService {


    @Resource
    private DzzhRepository dzzhRepository;

    @Resource
    private XczhRepository xczhRepository;

    @Resource
    private RestTemplateUtil restTemplateUtil;

    @Autowired
    private RestTemplate restTemplate;
    @Override
    public DzzhEarthquakeDisasterNum getDisasterNum(String code) {
        return dzzhRepository.getDisasterNum(code);
    }

    @Override
    public List<DzzhProvinceDisasterNum> getProvinceDisasterNum(String code) {
        List<DzzhProvinceDisasterNum> resultList = new ArrayList<>();
        List<EarthquakeDisasterNum> provinceDisasterNum = dzzhRepository.getProvinceDisasterNum(code);
        if(PlatformObjectUtils.isNotEmpty(provinceDisasterNum) && provinceDisasterNum.size()>0){
            for (EarthquakeDisasterNum earthquakeDisasterNum : provinceDisasterNum) {
                DzzhProvinceDisasterNum num = new DzzhProvinceDisasterNum();
                num.setId(earthquakeDisasterNum.getId());
                num.setCode(earthquakeDisasterNum.getCode());
                num.setProvince(earthquakeDisasterNum.getName());
                num.setProvinceBreakNum(earthquakeDisasterNum.getBreakNum());
                num.setProvinceLiquefyingNum(earthquakeDisasterNum.getLiquefyingNum());
                num.setProvinceLandslideNum(earthquakeDisasterNum.getLandslideNum());
                num.setProvinceSeismicSubsidenceNum(earthquakeDisasterNum.getSeismicSubsidenceNum());
                resultList.add(num);
            }
        }
        return resultList;
    }

    @Override
    public DzzhEarthquakeDisasterCountVO getDisasterCount() {
        DzzhEarthquakeDisasterCountVO result = new DzzhEarthquakeDisasterCountVO();
        List<DisasterVisitsCount> list = xczhRepository.getVisitNum("4");
        Map<String, Object> map = new HashMap<>();
        int todaySum = list.stream().mapToInt(DisasterVisitsCount::getTodayVisitNum).sum();
        int accumulateSum = list.stream().mapToInt(DisasterVisitsCount::getAccumulateVisitNum).sum();
        result.setNationwideTodayNum(todaySum);
        result.setNationwideAccumulateNum(accumulateSum);
        //按照日排序
        List<DisasterVisitsCount> sortedList = list.stream()
                .sorted(Comparator.comparing(DisasterVisitsCount::getTodayVisitNum).reversed())
                .collect(Collectors.toList());
        List<DzzhEarthquakeDisasterNumVO> threeUpTodayList = new ArrayList<>();
        for(int i=0;i<3;i++){
            DisasterVisitsCount disasterVisitsCount = sortedList.get(i);
            DzzhEarthquakeDisasterNumVO vo = new DzzhEarthquakeDisasterNumVO();
            vo.setProvince(disasterVisitsCount.getProvince());
            vo.setNum(disasterVisitsCount.getTodayVisitNum());
            threeUpTodayList.add(vo);
        }
        result.setToday(threeUpTodayList);
        //按月排序
        List<DisasterVisitsCount> sortedMonthList = list.stream()
                .sorted(Comparator.comparing(DisasterVisitsCount::getMonthVisitNum).reversed())
                .collect(Collectors.toList());
        List<DzzhEarthquakeDisasterNumVO> threeUpMonthList = new ArrayList<>();
        for(int i=0;i<3;i++){
            DisasterVisitsCount disasterVisitsCount = sortedMonthList.get(i);
            DzzhEarthquakeDisasterNumVO vo = new DzzhEarthquakeDisasterNumVO();
            vo.setProvince(disasterVisitsCount.getProvince());
            vo.setNum(disasterVisitsCount.getMonthVisitNum());
            threeUpMonthList.add(vo);
        }
        result.setMonth(threeUpMonthList);
        //按全部
        List<DisasterVisitsCount> sortedAllList = list.stream()
                .sorted(Comparator.comparing(DisasterVisitsCount::getAccumulateVisitNum).reversed())
                .collect(Collectors.toList());
        List<DzzhEarthquakeDisasterNumVO> threeUpAllList = new ArrayList<>();
        for(int i=0;i<3;i++){
            DisasterVisitsCount disasterVisitsCount = sortedAllList.get(i);
            DzzhEarthquakeDisasterNumVO vo = new DzzhEarthquakeDisasterNumVO();
            vo.setProvince(disasterVisitsCount.getProvince());
            vo.setNum(disasterVisitsCount.getAccumulateVisitNum());
            threeUpAllList.add(vo);
        }
       result.setAll(threeUpAllList);
        return result;
//        DzzhEarthquakeDisasterCountVO  vo =new DzzhEarthquakeDisasterCountVO();
//        Integer nationwideTodayNum=0;
//        Integer nationwideAccumulateNum=0;
//        List<DzzhEarthquakeDisasterCount> dzzhEarthquakeDisasterCounts=  dzzhRepository.getDisasterCount();
//        List<DzzhEarthquakeDisasterNumVO> today=new ArrayList<>();
//        List<DzzhEarthquakeDisasterNumVO> month=new ArrayList<>();
//        List<DzzhEarthquakeDisasterNumVO> all=new ArrayList<>();
//       if (PlatformObjectUtils.isNotEmpty(dzzhEarthquakeDisasterCounts)){
//           for (DzzhEarthquakeDisasterCount entity : dzzhEarthquakeDisasterCounts) {
//               DzzhEarthquakeDisasterNumVO todayVO=new DzzhEarthquakeDisasterNumVO();
//               DzzhEarthquakeDisasterNumVO monthVO=new DzzhEarthquakeDisasterNumVO();
//               DzzhEarthquakeDisasterNumVO allVO=new DzzhEarthquakeDisasterNumVO();
//               todayVO.setProvince(entity.getProvince());
//               todayVO.setNum(entity.getProvinceTodayNum());
//               monthVO.setProvince(entity.getProvince());
//               monthVO.setNum(entity.getProvinceMonthNum());
//               allVO.setProvince(entity.getProvince());
//               allVO.setNum(entity.getProvinceAllNum());
//               today.add(todayVO);
//               month.add(monthVO);
//               all.add(allVO);
//               nationwideTodayNum+=entity.getProvinceTodayNum();
//               nationwideAccumulateNum+=entity.getProvinceAllNum();
//           }
//       }
//        Collections.sort(today, (o1, o2) -> o2.getNum().compareTo(o1.getNum()));
//        Collections.sort(month, (o1, o2) -> o2.getNum().compareTo(o1.getNum()));
//        Collections.sort(all, (o1, o2) -> o2.getNum().compareTo(o1.getNum()));
//        vo.setToday(today);
//        vo.setMonth(month);
//        vo.setAll(all);
//        vo.setNationwideAccumulateNum(nationwideAccumulateNum);
//        vo.setNationwideTodayNum(nationwideTodayNum);
//        return  vo;
    }

    @Override
    public Map<String,List<DzzhRiskAreaAnalysis>> getRiskAreaAnalysis(String code) {
        List<DzzhRiskAreaAnalysis>  list=dzzhRepository.getRiskAreaAnalysis(code);
        Map<String, List<DzzhRiskAreaAnalysis>> collect = list.stream().sorted(Comparator.comparing(DzzhRiskAreaAnalysis::getRiskArea).reversed())
                .collect(Collectors.groupingBy(DzzhRiskAreaAnalysis::getRiskGrade));
        return collect;
    }

    @Override
    public List<DzzhEvaluationType> getMap(DzzhEvaluationTypeVO dzzhEvaluationTypeVO) {
        return dzzhRepository.getMap(dzzhEvaluationTypeVO);
    }

    @Override
    public List<DzzhEarthquakeOverviewLandslide> getOverviewLandslide() {
        return dzzhRepository.getOverviewLandslide();
    }

    @Override
    public List<DzzhEarthquakeOverviewLiquefying> getOverviewLiquefying() {
        return dzzhRepository.getOverviewLiquefying();
    }

    @Override
    public List<DzzhEarthquakeOverviewSeismicSubsidence> getOverviewSeismicSubsidence() {
        return dzzhRepository.getOverviewSeismicSubsidence();
    }

    @Override
    public List<DzzhEarthquakeOverviewSeismicSubsidence> getOverviewBreak() {
        return dzzhRepository.getOverviewBreak();
    }

    @Override
    public List<SurfaceRuptureZoneVo> getSurfaceRuptureZone(ZoneParam param) {
        return dzzhRepository.getSurfaceRuptureZone(param);
    }

    @Override
    public DisasterResponseVO getDisasterOverview(DisasterRequestVO disasterRequestVO,String code) {
        DisasterResponseVO vo=new DisasterResponseVO();
        DisasterResponse response=new DisasterResponse();
        DisasterResponse response1=new DisasterResponse();
        YesAndNo yesAndNo=new YesAndNo();
            for (int i = 0; i < 5; i++) {
                DzzhCountAreaResult  result=dzzhRepository.getDisasterOverview("地震滑坡-逻辑斯蒂模型",String.valueOf(Integer.valueOf(disasterRequestVO.getLandslideSecondType())+6),code,i+1);
                if (i==0){
                    if (PlatformObjectUtils.isEmpty(result)){
                        response.setPoleHighProportion(0.00);
                    }else {
                        response.setPoleHighProportion(result.getPercent());
                    }
                }else if (i==1){
                    if (PlatformObjectUtils.isEmpty(result)){
                        response.setHighProportion(0.00);
                    }else {
                        response.setHighProportion(result.getPercent());
                    }
                }else if (i==2){
                    if (PlatformObjectUtils.isEmpty(result)){
                        response.setCentreProportion(0.00);
                    }else {
                        response.setCentreProportion(result.getPercent());
                    }
                }else if (i==3){
                    if (PlatformObjectUtils.isEmpty(result)){
                        response.setPoleLowProportion(0.00);
                    }else {
                        response.setPoleLowProportion(result.getPercent());
                    }
                }else if (i==4){
                    if (PlatformObjectUtils.isEmpty(result)){
                        response.setLowProportion(0.00);
                    }else {
                        response.setLowProportion(result.getPercent());
                    }
                }
            }
        for (int i = 0; i < 4; i++) {
            DzzhCountAreaResult  result=dzzhRepository.getDisasterOverview("砂土液化-层次分析法",disasterRequestVO.getSandSecondType(),code,i+1);
            if (i==0){
                if (PlatformObjectUtils.isEmpty(result)){
                    response1.setPoleHighProportion(0.00);
                }else {
                    response1.setPoleHighProportion(result.getPercent());
                }
            }else if (i==1){
                if (PlatformObjectUtils.isEmpty(result)){
                    response1.setHighProportion(0.00);
                }else {
                    response1.setHighProportion(result.getPercent());
                }
            }else if (i==2){
                if (PlatformObjectUtils.isEmpty(result)){
                    response1.setCentreProportion(0.00);
                }else {
                    response1.setCentreProportion(result.getPercent());
                }
            }else if (i==3){
                if (PlatformObjectUtils.isEmpty(result)){
                    response1.setPoleLowProportion(0.00);
                }else {
                    response1.setPoleLowProportion(result.getPercent());
                }
            }else if (i==4){
                if (PlatformObjectUtils.isEmpty(result)){
                    response1.setLowProportion(0.00);
                }else {
                    response1.setLowProportion(result.getPercent());
                }
            }
        }
        vo.setLandslide(response);
        vo.setSand(response1);

        for (int i = 0; i < 2; i++) {
            DzzhCountAreaResult yan = dzzhRepository.getDisasterOverview("软土震陷", String.valueOf(Integer.valueOf(disasterRequestVO.getWeakSecondType() + 7)), code,i);
            if (i==0){
                if (PlatformObjectUtils.isEmpty(yan)){
                    yesAndNo.setYesProportion("0");
                }else {
                    yesAndNo.setYesProportion(String.valueOf(yan.getPercent()));
                }
            }else if (i==1){
                if (PlatformObjectUtils.isEmpty(yan)){
                    yesAndNo.setNoProportion("0");
                }else {
                    yesAndNo.setNoProportion(String.valueOf(yan.getPercent()));
                }
            }
         }
        vo.setYesAndNo(yesAndNo);
        return vo;
    }

    @Override
    public DzzhEarthquakeDisasterNum getMapDisaster(String type, String provinceCode) {
        //总数汇总
        List<Map<String, Object>> totleNum=dzzhRepository.getOneTotleNum(provinceCode);
        List<DzzhMapEarthquakeDisaster> mapDisaster = dzzhRepository.getOtherTotleNum(type, provinceCode);
        DzzhEarthquakeDisasterNum dzzhEarthquakeDisasterNum=new DzzhEarthquakeDisasterNum();
        dzzhEarthquakeDisasterNum.setMap(totleNum);
        dzzhEarthquakeDisasterNum.setList(mapDisaster);
        return dzzhEarthquakeDisasterNum;
    }

    @Override
    public List<LogisticGrowthEntity> getResultLogisticGrowth(String dzIntensity) {
        return dzzhRepository.getResultLogisticGrowth(dzIntensity);
    }

    @Override
    public List<SeimicLandslideEntity> getSeismicLandslide(String type, String dzIntensity,String code) {
        return dzzhRepository.getSeismicLandslide(type,dzIntensity,code);
    }

    @Override
    public List<SeimicLandslideEntity> getSandLiquefaction(String type, String dzIntensity,String code) {
        return dzzhRepository.getSandLiquefaction(type,dzIntensity,code);
    }

    @Override
    public List<SeimicLandslideEntity> getSoftEarth(String type, String dzIntensity,String code) {
        return dzzhRepository.getSoftEarth(type,dzIntensity,code);
    }

    @Override
    public void dzzhData() {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        //String url = configGroup.getProperty("dzzhRestUrl") + "dpzs/getDpzsEntityVO";
        //全国已有地震地质灾害数量
        List<EarthquakeDisasterNum> resultList = new ArrayList<>();
        List<DzzhMapEarthquakeDisaster> mapList = new ArrayList<>();
        final String geologicalDisasterNumUrl = configGroup.getProperty("dzzhRestUrl") + "landslideSite/listForDp";
        Map<String, Object> paramMap = new HashMap<>();
        ResponseEntity<JSONObject> geologicalDisasterNumResponseEntity = restTemplateUtil.sendHttpRequestjS(geologicalDisasterNumUrl, paramMap);
        if(geologicalDisasterNumResponseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
            System.out.println("111");
            Map<String, Object> data = (Map<String, Object>) geologicalDisasterNumResponseEntity.getBody().get("data");
            LinkedHashMap surfaceList = (LinkedHashMap) data.get("surface");
            Set<String> codeList = new HashSet<>();
            if(PlatformObjectUtils.isNotEmpty(surfaceList) && surfaceList.size()>0){
                codeList = surfaceList.keySet();
            }
            LinkedHashMap softList = (LinkedHashMap) data.get("soft");
            Set<String> softCodeList = new HashSet<>();
            if(PlatformObjectUtils.isNotEmpty(softList) && softList.size()>0){
                softCodeList = softList.keySet();
            }
            LinkedHashMap sandList = (LinkedHashMap) data.get("sand");
            Set<String> sandCodeList = new HashSet<>();
            if(PlatformObjectUtils.isNotEmpty(sandList) && sandList.size()>0){
                sandCodeList = sandList.keySet();
            }
            LinkedHashMap hpList = (LinkedHashMap) data.get("hp");
            Set<String> hpCodeList = new HashSet<>();
            if(PlatformObjectUtils.isNotEmpty(hpList) && hpList.size()>0){
                hpCodeList = hpList.keySet();

            }
            Set<String> combinedSet = new HashSet<>(codeList);
            combinedSet.addAll(softCodeList);
            combinedSet.addAll(sandCodeList);
            combinedSet.addAll(hpCodeList);
            EarthquakeDisasterNum earthquakeDisasterNum = new EarthquakeDisasterNum();
            int breakNum = 0;
            int seismicSubsidenceNum = 0;
            int liquefyingNum = 0;
            int landslideNum = 0 ;
            for (String code : combinedSet) {
                EarthquakeDisasterNum num1 = new EarthquakeDisasterNum();
                if(PlatformObjectUtils.isNotEmpty(surfaceList.get(code))){
                    BigDecimal surface = new BigDecimal(surfaceList.get(code).toString());
                    num1.setBreakNum(surface.intValue());
                    breakNum+=surface.intValue();
                }else{
                    num1.setBreakNum(0);
                }
                if(PlatformObjectUtils.isNotEmpty(softList.get(code))){
                    BigDecimal soft = new BigDecimal(softList.get(code).toString());
                    num1.setSeismicSubsidenceNum(soft.intValue());
                    seismicSubsidenceNum+=soft.intValue();
                }else{
                    num1.setSeismicSubsidenceNum(0);
                }
                if(PlatformObjectUtils.isNotEmpty(sandList.get(code))){
                    BigDecimal sand = new BigDecimal(sandList.get(code).toString());
                    num1.setLiquefyingNum(sand.intValue());
                    liquefyingNum+=sand.intValue();
                }else{
                    num1.setLiquefyingNum(0);
                }
                if(PlatformObjectUtils.isNotEmpty(hpList.get(code))){
                    BigDecimal hp = new BigDecimal(hpList.get(code).toString());
                    num1.setLandslideNum(hp.intValue());
                    landslideNum+=hp.intValue();
                }else{
                    num1.setLandslideNum(0);
                }
                num1.setId(UUIDGenerator.getUUID());
                num1.setCode(code.split("_")[0]);
                num1.setName(code.split("_")[1]);
                if(!"00".equals(num1.getCode().substring(2,4))){
                    //表示市一级
                    DzzhMapEarthquakeDisaster map = new DzzhMapEarthquakeDisaster();
                    map.setId(UUIDGenerator.getUUID());
                    map.setProvinceCode(num1.getCode().substring(0,2)+"0000");
                    map.setCity(num1.getName());
                    map.setCityCode(num1.getCode());
                    map.setNum(num1.getBreakNum());
                    // //1:地震滑坡 2:砂土液化 3：软土震陷 4：地表破裂带
                    map.setType("4");
                    mapList.add(map);
                    map = new DzzhMapEarthquakeDisaster();
                    map.setId(UUIDGenerator.getUUID());
                    map.setProvinceCode(num1.getCode().substring(0,2)+"0000");
                    map.setCity(num1.getName());
                    map.setCityCode(num1.getCode());
                    map.setNum(num1.getSeismicSubsidenceNum());
                    // //1:地震滑坡 2:砂土液化 3：软土震陷 4：地表破裂带
                    map.setType("3");
                    mapList.add(map);
                    map = new DzzhMapEarthquakeDisaster();
                    map.setId(UUIDGenerator.getUUID());
                    map.setProvinceCode(num1.getCode().substring(0,2)+"0000");
                    map.setCity(num1.getName());
                    map.setCityCode(num1.getCode());
                    map.setNum(num1.getLiquefyingNum());
                    // //1:地震滑坡 2:砂土液化 3：软土震陷 4：地表破裂带
                    map.setType("2");
                    mapList.add(map);
                    map = new DzzhMapEarthquakeDisaster();
                    map.setId(UUIDGenerator.getUUID());
                    map.setProvinceCode(num1.getCode().substring(0,2)+"0000");
                    map.setCity(num1.getName());
                    map.setCityCode(num1.getCode());
                    map.setNum(num1.getLandslideNum());
                    // //1:地震滑坡 2:砂土液化 3：软土震陷 4：地表破裂带
                    map.setType("1");
                    mapList.add(map);
                }
                resultList.add(num1);
            }
            earthquakeDisasterNum.setId(UUIDGenerator.getUUID());
            earthquakeDisasterNum.setBreakNum(breakNum);
            earthquakeDisasterNum.setLandslideNum(landslideNum);
            earthquakeDisasterNum.setLiquefyingNum(liquefyingNum);
            earthquakeDisasterNum.setSeismicSubsidenceNum(seismicSubsidenceNum);
            earthquakeDisasterNum.setCode("0");
            resultList.add(earthquakeDisasterNum);
            if(resultList.size()>0){

                dzzhRepository.delEarthquakeDisaster();
                dzzhRepository.saveEarthquakeDisaster(resultList);
            }
            if(mapList.size()>0){
                dzzhRepository.delMapEarthquakeDisaster();
                dzzhRepository.saveMapEarthquakeDisaster(mapList);
            }
        }

    }

    @Override
    public Map<String, Object> getByEstimate(HashMap<String,Object> param) {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        final String url = configGroup.getProperty("dzzhRestUrl") + "eqLandslide/largeScreen";
        ResponseEntity<JSONObject> cchResponseEntity = restTemplateUtil.sendHttpRequestjS(url, param);
        Map<String, Object> data = null;
        try {
            if(cchResponseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
                data = (Map<String, Object>) cchResponseEntity.getBody().get("data");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return data;
    }

    @Override
    public void getSurfaceRuptureZoneTask() {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("dzzhRestUrl") + "eqLandslide/getSurfaceRuptureZone";
        Map<String, Object> param = new HashMap<>();
        ResponseEntity<JSONObject> cchResponseEntity = restTemplateUtil.sendHttpRequestjS(url, param);
        List<SurfaceRuptureZoneVo> data = null;
        try {
            if(cchResponseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
                data = (List<SurfaceRuptureZoneVo>) cchResponseEntity.getBody().get("data");
                ObjectMapper mapper = new ObjectMapper();
                data = mapper.convertValue(data, new TypeReference<List<SurfaceRuptureZoneVo>>() { });
                dzzhRepository.delete();
                if(PlatformObjectUtils.isNotEmpty(data)){
                    for (SurfaceRuptureZoneVo item : data) {
                        item.setId(UUIDGenerator.getUUID());
                        dzzhRepository.save(item);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
